package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class shoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        ShoppingCart dbShoppingCart = shoppingCartMapper.findShoppingCart(shoppingCart);
        if (dbShoppingCart!=null){
            dbShoppingCart.setNumber(dbShoppingCart.getNumber()+1);
            shoppingCartMapper.updateNumber(dbShoppingCart.getId(), dbShoppingCart.getNumber());
        }else {
            dbShoppingCart=shoppingCart;
            dbShoppingCart.setCreateTime(LocalDateTime.now());
            dbShoppingCart.setNumber(1);
            shoppingCartMapper.save(dbShoppingCart);
        }
        return dbShoppingCart;
    }

    @Override
    public List<ShoppingCart> findAll(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findAll(userId);
        return shoppingCartList;
    }

    @Override
    public void clean(Long userId) {
        shoppingCartMapper.deleteByUserId(userId);
    }

    @Override
    public void updateNumber2(ShoppingCart shoppingCart) {
        ShoppingCart dbShoppingCart = shoppingCartMapper.findShoppingCart(shoppingCart);
        dbShoppingCart.setNumber(dbShoppingCart.getNumber()-1);
        if (dbShoppingCart.getNumber()==0){
            shoppingCartMapper.delete(dbShoppingCart);
        }else {
            shoppingCartMapper.updateNumber2(dbShoppingCart);
        }
    }
}
